"""
https://blog.csdn.net/saltriver/article/details/79680859
图像“颜色选择”怎么用？
https://blog.csdn.net/saltriver/article/details/79680973
选择图像的“感兴趣区域”
https://blog.csdn.net/saltriver/article/details/80547245
Hough直线检测的理解
"""

import cv2 as cv
import numpy as np

np.random.seed(1)

###############################################################
# load
img_path = '../../../../large_data/pic/lane/lane.jfif'
img = cv.imread(img_path, cv.IMREAD_COLOR)
cv.imshow('original', img)
img_ = img.copy()
img = cv.cvtColor(img, cv.COLOR_BGR2HSV)

###############################################################
# yellow and white color selection
# white
lower_white = np.array([0, 0, 200])   # ATTENTION White in HSV, remember it.
upper_white = np.array([180, 40, 255])
# yellow
lower_yellow = np.array([15, 50, 50])
upper_yellow = np.array([35, 255, 255])
# select
white = cv.inRange(img, lower_white, upper_white)
yellow = cv.inRange(img, lower_yellow, upper_yellow)
cv.imshow("white", white)
cv.imshow("yellow", yellow)

###############################################################
# mix
mixed = cv.bitwise_or(white, yellow)
cv.imshow("mixed", mixed)

###############################################################
# mask for chopping
# 获取原始图像的行和列
row, col = img.shape[:2]
# 定义多边形的顶点
bottom_left = [col * 0.05, row]
top_left = [col * 0.45, row * 0.6]
top_right = [col * 0.55, row * 0.6]
bottom_right = [col * 0.95, row]
# 使用顶点定义多边形
vertices = np.array([bottom_left, top_left, top_right, bottom_right], dtype=np.int32)
# make mask
roi_mask = np.zeros((row, col), dtype=np.uint8)
cv.fillPoly(roi_mask, [vertices], 255)
cv.imshow("roi_mask", roi_mask)

###############################################################
# chop
roi = cv.bitwise_and(mixed, mixed, mask=roi_mask)
cv.imshow("roi", roi)

###############################################################
# get skeletons (silhouette)
# 高斯模糊，Canny边缘检测需要的
lane = cv.GaussianBlur(roi, (5, 5), 0)
# 进行边缘检测，减少图像空间中需要检测的点数量
lane = cv.Canny(lane, 50, 150)
cv.imshow("silhouette", lane)

###############################################################
# HoughLines
rho = 1  # 距离分辨率
theta = np.pi / 180  # 角度分辨率
threshold = 10  # 霍夫空间中多少个曲线相交才算作正式交点
min_line_len = 10  # 最少多少个像素点才构成一条直线  # ATTENTION 为啥这个变量没有用到呢？
max_line_gap = 50  # 线段之间的最大间隔像素
lines = cv.HoughLinesP(lane, rho, theta, threshold, minLineLength=min_line_len, maxLineGap=max_line_gap)
print(f'识别出的直线数量：{len(lines)}')
line_img = np.zeros_like(img)
stat = []
for line in lines:
    stat.append(len(line))
    for x1, y1, x2, y2 in line:
        cv.line(line_img, (x1, y1), (x2, y2), (
            np.random.randint(0, 256),
            np.random.randint(0, 256),
            np.random.randint(0, 256),
        ), 1)
cv.imshow("Hough Lines", line_img)
stat = np.int32(stat)
print(f'Stat: {np.unique(stat)}')

###############################################################
# Termination
print('图片上按任意键退出。')
cv.waitKey(0)
cv.destroyAllWindows()
